package no.nordicsemi.android.nrfmesh.auth.util;

import java.security.MessageDigest;
import java.security.SecureRandom;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;

/** 本地 PBKDF2 密码工具：避免明文存储 */
public final class Passwords {
    private static final String ALG = "PBKDF2WithHmacSHA256";
    private static final int ITER = 120_000;
    private static final int KEYLEN = 32; // 32 bytes = 256 bits

    public static byte[] salt() {
        byte[] s = new byte[16];
        new SecureRandom().nextBytes(s);
        return s;
    }

    public static byte[] hash(char[] pw, byte[] salt) throws Exception {
        PBEKeySpec spec = new PBEKeySpec(pw, salt, ITER, KEYLEN * 8);
        return SecretKeyFactory.getInstance(ALG).generateSecret(spec).getEncoded();
    }

    public static boolean verify(char[] pw, byte[] salt, byte[] expect) throws Exception {
        return MessageDigest.isEqual(hash(pw, salt), expect);
    }
}
